package com.yuhao.init.utils;



import com.luciad.imageio.webp.WebPWriteParam;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: yuhao
 * @Date: 2024/5/7 9:50
 */
public class ImgToWebpUtils {



/*    public static File toWebpFile(String imgFilePath) {
        File imgFile = new File(imgFilePath);
        File webpFile = new File(imgFilePath + ".webp");
        try {
            BufferedImage bufferedImage = ImageIO.read(imgFile);
            ImageIO.write(bufferedImage, "webp", webpFile);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return webpFile;
    }*/

    /**
     * JPG格式图片转成webp格式(也可以是其他格式图片)
     * @param inputStream c:/1.test.jpg
     * @param fileName c:/1.test.webp
     * @return
     */
    public static void imgToWebp(InputStream inputStream, String fileName) {

        try {
            // 获取原始文件的编码
            BufferedImage image = ImageIO.read(inputStream);
            // 创建WebP ImageWriter实例
            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
            // 配置编码参数
            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
            // 设置压缩模式
            writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);
            // 配置ImageWriter输出
            writer.setOutput(new FileImageOutputStream(new File(System.getProperty("user.dir")+"\\src\\main\\resources\\tempFile\\" +fileName)));
            // 进行编码，重新生成新图片
            writer.write(null, new IIOImage(image, null, null), writeParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/**
     * webp格式图片转成JPG格式
     * @param oldfile c:/1.test.webp
     * @param newfile c:/1.test.jpg
     * @return
     *//*

    public static void webpToJpg(String oldfile, String newfile) {
        // 创建WebP ImageReader实例
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
        // 配置解码参数
        WebPReadParam readParam = new WebPReadParam();
        readParam.setBypassFiltering(true);
        // 在ImageReader设置读取的原文件
        try {
            reader.setInput(new FileImageInputStream(new File(oldfile)));
            // 解码图像
            BufferedImage image = reader.read(0, readParam);
            // 设置输入文件的格式和文件名
            ImageIO.write(image, "jpg", new File(newfile)); // 这里也可以使用其他图片格式，但是格式和文件名后缀要保持一致
            System.out.println("webp文件转成png格式成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/


}
